package com.hmall.controller;


import com.hmall.common.utils.AliyunOSSOperator;
import com.hmall.common.utils.PDFUtils;
import com.hmall.domain.po.File;
import com.hmall.domain.po.Result;
import com.hmall.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/file")
//@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET,
//        RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE,RequestMethod.OPTIONS})
public class FileController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @Autowired
    private IFileService fileService;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("userId") String userId,@RequestParam("file") MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String originalFilename = file.getOriginalFilename();// 获取文件名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));// 获取文件后缀
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + extension;

            // 读取PDF内容
            String content = PDFUtils.pdfToString(file.getInputStream());

            // 将内容存储到Redis（可选）
            // redisTemplate.opsForHash().put("healthReport", idCardNo, content);
            // redisTemplate.expire("healthReport", 5, TimeUnit.MINUTES);
            File filePO = new File();
            filePO.setUserId(Integer.parseInt(userId));
            filePO.setContent(content);
            fileService.save(filePO);

            // 上传至阿里云OSS并返回URL
            String url = aliyunOSSOperator.upload(file.getBytes(), fileName);

            // 构造响应结果
            Result ajax = Result.success();
            return ajax;

        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/get")
    public String getFile(@RequestParam("userId") String userId){
        return fileService.getFile(userId);
    }
}
